
package net.neiquan.neiquandemowithkf.api;


import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import net.neiquan.neiquandemowithkf.activity.MainActivity;
import net.neiquan.neiquandemowithkf.application.MyApplication;
import net.neiquan.neiquandemowithkf.entity.User;
import net.neiquan.neiquandemowithkf.utils.Tools;

import net.neiquanlib.http.NetCallBack;
import net.neiquanlib.http.ResultModel;
import net.neiquanlib.utils.JsonFormatUtils;
import net.neiquanlib.utils.LogC;

import org.apache.http.Header;
import org.apache.http.entity.ByteArrayEntity;
import org.haitao.common.utils.NetWorkUtil;
import org.haitao.common.utils.ToastUtil;

import java.util.List;

/**
 * Description http 请求
 * Author by wangHaitao(a758277560@gmail.com)
 * Created  on 2015/12/3
 * Version 1.0
 */
public class HttpUtil {

    /**
     * 请求失败:服务器错误
     */
    public static final int ERROR_SERVER = 500;

    /**
     * 请求失败:URL 无效
     */
    public static final int ERROR_URL = 404;
    /**
     * 请求失败: 请求无法理解
     */
    public static final int ERROR_REQUEST = 400;

    /**
     * 请求失败:服务器没有响应
     */
    public static final int ERROR_RESNPONSE = 0;

    /**
     * 请求失败:服务器请求 返回 false
     */
    public static final int ERROR_FALSE = 222;
    /**
     * 请求失败:服务器请求 返回 不是json
     */
    public static final int ERROR_DATA = 333;
    /**
     * 请求失败:网络不可用
     */
    public static final int ERROR_NETWORK = 444;

    public static AsyncHttpClient client = new AsyncHttpClient();

    public static boolean inHome;

    private static void post(final String url, RequestParams params, final NetCallBack callback, @SuppressWarnings("rawtypes") final Class type, final boolean isList, final String requestJson) {

        // 网络是否可用
        if (checkNet(callback)) {

            if (params == null) {
                params = new RequestParams();
            }
            params.put("deviceType", "1");// android
            User mUser = MyApplication.getInstance().mUser;
            if (mUser != null) {
                params.put("userToken", mUser.getUserToken());
            }
            LogC.e("url=" + url + "\ndatas= " + params);
            //测试 请求超时 12秒
            client.setTimeout(12000);
            final RequestParams tmepparams = params;

            if (requestJson == null) {
                client.post(url, params, new AsyncHttpResponseHandler() {

                    @Override
                    public void onCancel() {
                        super.onCancel();
                        if (callback != null) {
                            callback.onCancel();
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        if (callback != null) {
                            callback.onFinish();
                        }
                    }

                    @Override
                    public void onProgress(int bytesWritten, int totalSize) {
                        super.onProgress(bytesWritten, totalSize);
                        if (callback != null) {
                            callback.onProgress(bytesWritten, totalSize);
                        }
                    }

                    @Override
                    public void onStart() {
                        super.onStart();
                        if (callback != null) {
                            callback.onStart();
                        }
                    }

                    @Override
                    public void onFailure(int error_code, Header[] headers, byte[] bytes, Throwable throwable) {
                        LogC.e("post--fail" + "\t" + " url=" + url + "\t" + "error_code=" + error_code + "\t" + "data=" + tmepparams);
                        handleFail(callback, error_code, headers, bytes, throwable);
                    }

                    @Override
                    public void onSuccess(int arg0, Header[] headers, byte[] responseBt) {
                        handleSuccess(arg0, headers, responseBt, url, tmepparams, callback, type, isList);
                    }

                });
            } else {
                LogC.e("url=" + url + "\ndatas= " + requestJson);
                ByteArrayEntity entity = new ByteArrayEntity(requestJson == null ? "".getBytes() : requestJson.getBytes());
                client.post(MyApplication.getInstance(), url, entity, "application/json", new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int arg0, Header[] headers, byte[] responseBt) {
                        handleSuccess(arg0, headers, responseBt, url, tmepparams, callback, type, isList);
                    }

                    @Override
                    public void onFailure(int error_code, Header[] headers, byte[] bytes, Throwable throwable) {
                        LogC.e("post--fail" + "\t" + " url=" + url + "\t" + "error_code=" + error_code + "\t" + "data=" + requestJson);
                        handleFail(callback, error_code, headers, bytes, throwable);
                    }
                });

            }

        }
    }

    /**
     * 请求前判断网络
     *
     * @param callback
     * @return
     */
    private static boolean checkNet(final NetCallBack callback) {
        if (!NetWorkUtil.isNetworkAvailable(MyApplication.getInstance())) {
            ToastUtil.shortShowCustom("当前网络不可用！");
            if (callback != null) {
                callback.onFail("当前网络不可用。", ERROR_NETWORK, false);
            }
            return false;
        }
        return true;
    }


    /**
     * 处理失败
     */
    private static void handleFail(final NetCallBack callback, int error_code, Header[] headers, byte[] bytes, Throwable throwable) {
        String error = "其它未知错误!";

        if (error_code == 0) {
            LogC.e("ser not response");
            error = "连接超时，请稍候重试。";
        } else if (error_code == 404) {
            LogC.e("url not found");
            //error = "请求地址不存在，请稍候重试。";
            error = "网络请求失败，请稍候重试。";
        } else if (error_code == 500) {
            //error = "服务器出错误了，请稍候重试。";
            LogC.e("server error");
            error = "网络请求失败，请稍候重试。";
        } else if (error_code == 400) {
            error = "请求出错了，请稍候重试。";
            //LogC.e("server error");
            error = "网络请求失败，请稍候重试。";
        } else {
            //error = "其它未知错误，请稍候重试。";
            error = "网络请求失败，请稍候重试。";
        }
        ToastUtil.shortShowToast(error);
        if (callback != null) {
            callback.onFail(error, error_code, false);
        }
    }

    /**
     * 请求结果统一解析
     *
     * @param arg0
     * @param headers
     * @param responseBt
     * @param url
     * @param params
     * @param callback
     * @param type
     * @param isList
     */
    @SuppressWarnings("unchecked")
    public static void handleSuccess(int arg0, Header[] headers, byte[] responseBt, final String url, RequestParams params, final NetCallBack callback, @SuppressWarnings("rawtypes") final Class type, final boolean isList) {
        if (responseBt == null) {
            responseBt = new byte[]{};
        }
        String jsonString = new String(responseBt);
        LogC.e(url + "data" + jsonString);
        LogC.e("url=" + url + "\n RequestParams=" + params.toString() + "\n result=" + JsonFormatUtils.formatJson(jsonString));
        // 放在这里解析json 数据
        if (callback != null) {
            JSONObject json = null;
            int code = 0;
            String message = null;
            String response = null;
            try {
                json = JSON.parseObject(jsonString);
                if (json.containsKey("errorMessage")) {
                    message = json.getString("errorMessage");
                }
                if (json.containsKey("response")) {
                    response = json.getString("response");
                }
                code = json.getIntValue("code");
            } catch (JSONException e) {
                e.printStackTrace();
                ToastUtil.shortShowToast("数据解析错误，请稍候重试");
                if (callback != null) {
                    callback.onFail("", ERROR_DATA, true);
                }
                // 后面不要执行
                return;
            }
            // 响应成功
            if (code == 0) {
                if (type != null) {
                    // json 解析 有数据
                    if (response != null && !"".equals(response) && !"null".equals(response)) {
                        ResultModel body = new ResultModel();
                        try {
                            if (isList) {
                                List<?> ls = JSON.parseArray(response, type);
                                body = new ResultModel();
                                body.setModelList(ls);
                            } else {
                                body.setModel(JSON.parseObject(response, type));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            ToastUtil.shortShowToast("数据解析错误，请稍候重试");
                            if (callback != null) {
                                callback.onFail("", ERROR_DATA, true);
                            }
                            return;
                        }
                        // 不该 try 的地方不要try  下面的代码不应该try
                        if (callback != null) {
                            callback.onSuccess(message, code, response, body);
                        }

                    } else {
                        // 没有model
                        if (callback != null) {
                            ResultModel body = new ResultModel();
                            callback.onSuccess(message, code, "", body);
                        }
                    }
                } else {
                    // 没有model
                    if (callback != null) {
                        callback.onSuccess(message, code, response, null);
                    }
                }

            } else {

                if (16 == code || 21 == code) {// 21 账号被禁用
                    // 消失对话框
                    if (callback != null) {
                        callback.onFail(message, code, true);
                    }
                    Tools.dismissWaitDialog();// 很重要！！！！
                    //
                    String runningActivity = null;
                    try {
                        ActivityManager am = (ActivityManager) MyApplication.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
                        runningActivity = am.getRunningTasks(1).get(0).topActivity.getClassName();
                    } catch (Exception e) {

                    }
                    LogC.e("sessionout-------------" + code);
                    // 登录
                    if (!inHome) {
                        LogC.e("sessionout-------------skip" + code);
                        inHome = true;
                        Tools.dismissWaitDialog();
                        Intent intent = new Intent(MyApplication.getInstance(), MainActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.putExtra("sessionOut", true);
                        MyApplication.getInstance().startActivity(intent);
                    }

                } else {
                    if (callback != null) {
                        callback.onFail(message, code, true);
                    }
                }

            }

        }

    }

    public static void post(String url, RequestParams params, final NetCallBack callback, final Class type) {
        post(url, params, callback, type, false, null);
    }

    public static void postList(String url, RequestParams params, final NetCallBack callback, final Class type) {
        post(url, params, callback, type, true, null);
    }

    public static void postBodyList(String url, String json, final NetCallBack callback, final Class type) {
        post(url, null, callback, type, true, json);
    }

    public static void postBody(String url, String json, final NetCallBack callback, final Class type) {
        post(url, null, callback, type, false, json);
    }

}